package com.dfk.bs.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dfk.bs.common.constants.ResultCodeEnum;
import com.dfk.bs.common.exception.BsException;
import com.dfk.bs.common.vo.R;
import com.dfk.bs.entity.Eleapp;
import com.dfk.bs.service.EleappService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用电器表 前端控制器
 * </p>
 *
 * @author DDK
 * @since 2019-12-12
 */
@Api("用电器电器管理")
@CrossOrigin //跨域
@RestController
@RequestMapping("/ddkbishe/eleapp")
public class EleappController {

    @Autowired
    private EleappService eleappService;


    @ApiOperation("所有用电器列表")
    @GetMapping("/list")
    public R list(){

        List<Eleapp> list = eleappService.list(null);

        return R.ok()
                .message("查询用电器列表成功")
                .data("items",list);
    }

    @ApiOperation("新增用电器")
    @PostMapping("/save")
    public R save(
            @ApiParam(name="eleapp",value = "用电器基本信息",required = true)
            @RequestBody Eleapp eleapp){
        eleappService.save(eleapp);
        return R.ok()
                .message("新增用电器成功");
    }



    @ApiOperation("根据id删除用电器")
    @DeleteMapping("/remove/{eleappid}")
    public R removeById(
            @ApiParam(name = "eleappid",value = "eleappid", required = true)
            @PathVariable String eleappid){
        eleappService.removeById(eleappid);

        return R.ok()
                .message("删除用电器成功");
    }
    @ApiOperation("分页条件查询用电器列表")
    @PostMapping("/pageQuery")
    public R pageQuery(@RequestBody Map<String, Object> params){

        Integer page = (Integer) params.get("page");
        Integer limit = (Integer) params.get("limit");

        String selectname = (String) params.get("selectname");

        //业务逻辑错误，抛出自定义异常
        if(page <= 0 || limit <= 0){
            throw new BsException(ResultCodeEnum.PARAM_ERROR);
        }
        Page<Eleapp> pageParam=new Page<>(page,limit);

        /*已经把查询的每一页的信息放到 pageParam中*/
        eleappService.pageQuery(pageParam,selectname);

        List<Eleapp> records = pageParam.getRecords();
        long total = pageParam.getTotal();

        return R.ok()
                .message("分页条件查询用电器列表成功")
                .data("total",total)
                .data("rows",records);
    }

    @ApiOperation(value = "根据ID修改用电器")
    @PutMapping("/update")
    public R updateById(
            @ApiParam(name = "eleapp", value = "用电器对象", required = true)
            @RequestBody Eleapp eleapp){
        eleappService.updateById(eleapp);
        return R.ok()
                .message("修改用电器成功");
    }
}

